import {Component} from "@angular/core";
import {LoginService} from "./login.service";
import { ToastController } from 'ionic-angular';
import { NavController } from 'ionic-angular';
import { Events } from 'ionic-angular';
import {SERVER_BASE_URL} from "../../utils/contansts";

@Component({
  selector:"page-login",
  templateUrl: "login.html",
  providers: [LoginService]
})
export class LoginPage {
  private username: string;
  private password: string;

  constructor(private navCtrl: NavController,private loginService: LoginService,
              private toastCtrl: ToastController,private events: Events) {
  }

  doLogin(form) {
    if (form.valid) {
      this.loginService.login(SERVER_BASE_URL.LOGIN_URL, this.username, this.password);
    }
  }

  ionViewDidLoad() {
    this.eventHandler();
  }
  ionViewWillUnload() {
    this.destroyEventHandler();
  }
  eventHandler(){
// second page (listen for the user created event)
    this.events.subscribe('user:login:success', (username) => {
      let toast = this.toastCtrl.create({
        message: 'login successfully',
        duration: 2000
      });
      toast.present();
      this.navCtrl.pop();
    });
    this.events.subscribe('user:login:error',(err)=>{
      let toast = this.toastCtrl.create({
        message: err+"",
        duration: 2000
      });
      toast.present();
    });
  }
  destroyEventHandler(){
    this.events.unsubscribe("user:login:success");
    this.events.unsubscribe("user:login:error");
  }
}
